package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.http.HttpContentType;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyRongYiHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeRongYiHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * 安心分期（出）&融逸花 全流程37
 *
 * @author 江小游
 */
@ApiPlan(productId = "266", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatRongYiHua implements ApiPlatformPhoneMd5ConvertHandler {
    private static final String KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArx5jeMD6326nl4SYlXl+ruhjtzdzSrnM0Xf+hVOwr/cOPLb4tFKFGNdzDGo1cAMTSSqf+tLrdS9tuNQxHhKVg63khvbM9HmSBxMR5xBDcSRvzNT9OspmAr6104DolhYX1/v7b2HZiFznaWuGDBVUV8xqjQKElOPp8HK+NjRtjmd8hnZ69J6Cx1U48Z0TQVA/YoKiPIoPwPdztHsE8v6aE7Bw1ymk/iuNefjGtcf1/0jclozIN87QMsfhcNbxSwi3dwqIZRbBzyMLSnmaXKiT1lWQz6vsC+2dUO7kcfITp+V3fToDC9sObav+5cab6ylY6gPaF4QRe8nyTHP4fSQnGQIDAQAB";
    private static final String CHANNEL_CODE = "11230";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataChangeMessage) throws Exception {
        apiDataChangeMessage.setHttpContentType(HttpContentType.APPLICATION_FORM_URLENCODED);
        //  撞库流程
        ApiPlatDataExchangeRongYiHua apiPlatDataExchange = new ApiPlatDataExchangeRongYiHua();
        // 拓展
        com.ts.api.module.api.convert.core.utils.ApiFieldConverter apiFieldConverter = com.ts.api.module.api.convert.core.utils.ApiFieldConverter.create(apiDataChangeMessage);
        // 手机号md5
        apiPlatDataExchange.setPhoneMd5(apiDataChangeMessage.getPhoneMd5().toLowerCase());
        // 掩码
        apiPlatDataExchange.setPhoneMask(apiDataChangeMessage.getPhoneMask());
        // 用户名
        apiPlatDataExchange.setUserName("浩安星");
        // 渠道号
        apiPlatDataExchange.setChannelCode(CHANNEL_CODE);
        // 城市
        apiPlatDataExchange.setCity(apiDataChangeMessage.getCity());
        // ip
        if (ValidParam.isNotEmpty(apiDataChangeMessage.getIp())) {
            apiPlatDataExchange.setIp(apiDataChangeMessage.getIp());
        } else {
            apiPlatDataExchange.setIp("127.0.0.1");
        }
        // 年龄
        apiPlatDataExchange.setAge(apiDataChangeMessage.getAge());
        // 性别
        String sex = ChooseEq.create(apiDataChangeMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatDataExchange.setSex(sex);
        // 贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataChangeMessage.getLoanAmount(), "1", 3)
                .when(apiDataChangeMessage.getLoanAmount(), "2", 5)
                .when(apiDataChangeMessage.getLoanAmount(), "3", 10)
                .when(apiDataChangeMessage.getLoanAmount(), "4", 20)
                .end(3);
        apiPlatDataExchange.setLoanAmount(money);
        // 贷款期限
        String value = ChooseEq.create(apiDataChangeMessage.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatDataExchange.setLoanTerm(value);
        // 职业(200:上班族,300:自由职业,400:企业主,500:个体户,800:公务员,900:其他),默认传200;
        String career = ChooseEq.create(apiDataChangeMessage.getCareer())
                .when("1", "200")
                .when("2", "300")
                .when("3", "400")
                .when("4", "900")
                .when("5", "500")
                .end("200");
        apiPlatDataExchange.setCareer(career);
        // 月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataChangeMessage.getMonthlySalary(), "1", 3000)
                .when(apiDataChangeMessage.getMonthlySalary(), "2", 8000)
                .when(apiDataChangeMessage.getMonthlySalary(), "3", 15000)
                .when(apiDataChangeMessage.getMonthlySalary(), "4", 30000)
                .when(apiDataChangeMessage.getMonthlySalary(), "5", 50000)
                .end(3000);
        apiPlatDataExchange.setMonthlySalary(monthlySalary);
        // 工资发放形式(10:银行卡,20:现金,30:自存),默认传10;
        String salaryPayMethod = ChooseEq.create(apiDataChangeMessage.getSalaryPayMethod())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setSalaryPayMethod(salaryPayMethod);
        // 单位工龄 10.0-6个月 20.6-12个月 30.12个月以上
        String yearsService = ChooseEq.create(apiDataChangeMessage.getYearsService())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setYearsService(yearsService);
        // 公积金(0:无公积金,10:缴纳未满6个月,20:缴纳6个月以上)
        String providentFund = ChooseEq.create(apiDataChangeMessage.getProvidentFund())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatDataExchange.setProvidentFund(providentFund);
        // 社保(0:无社保,10:缴纳未满6个月,20:缴纳6个月以上)
        String socialSecurity = ChooseEq.create(apiDataChangeMessage.getSocialSecurity())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatDataExchange.setSocialSecurity(socialSecurity);
        // 房产情况(0:无房产,10:有房产，不抵押,20:有房产，可抵押)
        String realEstateInfo = ChooseEq.create(apiDataChangeMessage.getRealEstateInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "20")
                .when("5", "10")
                .when("6", "20")
                .end("0");
        apiPlatDataExchange.setRealEstateInfo(realEstateInfo);
        // 车产情况(0:无车产,10:有车产，不抵押,20:有车产，可抵押)
        String carInfo = ChooseEq.create(apiDataChangeMessage.getCarInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatDataExchange.setCarInfo(carInfo);
        // 保单情况(0:无保险保单,10:缴纳未满1年,20:缴纳1年以上)
        String insurancePolicy = ChooseEq.create(apiDataChangeMessage.getInsurancePolicy())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatDataExchange.setInsurancePolicy(insurancePolicy);
        // 芝麻分(0:无芝麻分,10:600分以下,20:600~650分,30:650~700分,40:700分以上)
        String sesameCredit = ChooseEq.create(apiDataChangeMessage.getSesameCredit())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .when("4", "40")
                .end("0");
        apiPlatDataExchange.setSesameCredit(sesameCredit);
        // 营业执照注册年限(0:未注册,10:注册1年以下,20:注册1~5年,30:注册5年以上)
        String bizLicenseYear = ChooseEq.create(apiDataChangeMessage.getBizLicenseYear())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "30")
                .end("0");
        apiPlatDataExchange.setBizLicenseYear(bizLicenseYear);
        // 经营流水(单位万元)
        String bizBankDetails = ChooseEq.create(apiDataChangeMessage.getBizBankDetails())
                .when("1", "50")
                .when("2", "100")
                .when("3", "500")
                .end("50");
        apiPlatDataExchange.setBizBankDetails(bizBankDetails);
        // 对公账户收入(单位万元)
        String bizPubAccBankDetails = ChooseEq.create(apiDataChangeMessage.getBizPubAccBankDetails())
                .when("1", "50")
                .when("2", "100")
                .when("3", "500")
                .end("50");
        apiPlatDataExchange.setBizPubAccBankDetails(bizPubAccBankDetails);
        // 信用卡额度
        String creditLimit = ChooseEq.create()
                .when(apiDataChangeMessage.getCreditLimit(), "1", "0")
                .when(apiDataChangeMessage.getCreditLimit(), "2", "10")
                .when(apiDataChangeMessage.getCreditLimit(), "3", "10")
                .when(apiDataChangeMessage.getCreditLimit(), "4", "10")
                .when(apiDataChangeMessage.getCreditLimit(), "5", "10")
                .when(apiDataChangeMessage.getCreditLimit(), "6", "10")
                .end("0");
        apiPlatDataExchange.setCreditLimit(creditLimit);

        String aesKey = generateAESKey();
        String encryptedData = encryptData(JsonUtils.toJson(apiPlatDataExchange), aesKey);
        String encryptAesKey = encryptKey(KEY, aesKey);
        JSONObject json = new JSONObject();
        json.put("content", encryptedData);
        json.put("key", encryptAesKey);
        String encryptParam = json.toJSONString();
        String reqParam = Base64.getEncoder().encodeToString(encryptParam.getBytes(StandardCharsets.UTF_8));
        return MapUtils.<String, Object>newHashMap(newMap -> newMap.put("data", reqParam));
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyMessage) throws Exception {
        //  进件流程
        apiApplyMessage.setHttpContentType(HttpContentType.APPLICATION_FORM_URLENCODED);
        ApiPlatApplyRongYiHua apiPlatApply = new ApiPlatApplyRongYiHua();
        com.ts.api.module.api.convert.core.utils.ApiFieldConverter apiFieldConverter = com.ts.api.module.api.convert.core.utils.ApiFieldConverter.create(apiApplyMessage);

        apiPlatApply.setPhone(apiApplyMessage.getPhone());
        apiPlatApply.setUserName(apiApplyMessage.getUserName());
        apiPlatApply.setChannelCode(CHANNEL_CODE);
        apiPlatApply.setCity(apiApplyMessage.getCity());
        apiPlatApply.setAge(apiFieldConverter.getAgeInt());
        // ip
        if (ValidParam.isNotEmpty(apiApplyMessage.getIp())) {
            apiPlatApply.setIp(apiApplyMessage.getIp());
        } else {
            apiPlatApply.setIp("127.0.0.1");
        }
        // 性别
        String sex = ChooseEq.create(apiApplyMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatApply.setSex(sex);
        // 贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyMessage.getLoanAmount(), "1", 3)
                .when(apiApplyMessage.getLoanAmount(), "2", 5)
                .when(apiApplyMessage.getLoanAmount(), "3", 10)
                .when(apiApplyMessage.getLoanAmount(), "4", 20)
                .end(3);
        apiPlatApply.setLoanAmount(money);
        // 贷款期限
        String value = ChooseEq.create(apiApplyMessage.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatApply.setLoanTerm(value);
        // 职业(200:上班族,300:自由职业,400:企业主,500:个体户,800:公务员,900:其他),默认传200;
        String career = ChooseEq.create(apiApplyMessage.getCareer())
                .when("1", "200")
                .when("2", "300")
                .when("3", "400")
                .when("4", "900")
                .when("5", "500")
                .end("200");
        apiPlatApply.setCareer(career);
        // 月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiApplyMessage.getMonthlySalary(), "1", 3000)
                .when(apiApplyMessage.getMonthlySalary(), "2", 8000)
                .when(apiApplyMessage.getMonthlySalary(), "3", 15000)
                .when(apiApplyMessage.getMonthlySalary(), "4", 30000)
                .when(apiApplyMessage.getMonthlySalary(), "5", 50000)
                .end(3000);
        apiPlatApply.setMonthlySalary(monthlySalary);
        // 工资发放形式(10:银行卡,20:现金,30:自存),默认传10;
        String salaryPayMethod = ChooseEq.create(apiApplyMessage.getSalaryPayMethod())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatApply.setSalaryPayMethod(salaryPayMethod);
        // 单位工龄 10.0-6个月 20.6-12个月 30.12个月以上
        String yearsService = ChooseEq.create(apiApplyMessage.getYearsService())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatApply.setYearsService(yearsService);
        // 公积金(0:无公积金,10:缴纳未满6个月,20:缴纳6个月以上)
        String providentFund = ChooseEq.create(apiApplyMessage.getProvidentFund())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatApply.setProvidentFund(providentFund);
        // 社保(0:无社保,10:缴纳未满6个月,20:缴纳6个月以上)
        String socialSecurity = ChooseEq.create(apiApplyMessage.getSocialSecurity())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatApply.setSocialSecurity(socialSecurity);
        // 房产情况(0:无房产,10:有房产，不抵押,20:有房产，可抵押)
        String realEstateInfo = ChooseEq.create(apiApplyMessage.getRealEstateInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "20")
                .when("5", "10")
                .when("6", "20")
                .end("0");
        apiPlatApply.setRealEstateInfo(realEstateInfo);
        // 车产情况(0:无车产,10:有车产，不抵押,20:有车产，可抵押)
        String carInfo = ChooseEq.create(apiApplyMessage.getCarInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatApply.setCarInfo(carInfo);
        // 保单情况(0:无保险保单,10:缴纳未满1年,20:缴纳1年以上)
        String insurancePolicy = ChooseEq.create(apiApplyMessage.getInsurancePolicy())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end("0");
        apiPlatApply.setInsurancePolicy(insurancePolicy);
        // 芝麻分(0:无芝麻分,10:600分以下,20:600~650分,30:650~700分,40:700分以上)
        String sesameCredit = ChooseEq.create(apiApplyMessage.getSesameCredit())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .when("4", "40")
                .end("0");
        apiPlatApply.setSesameCredit(sesameCredit);
        // 营业执照注册年限(0:未注册,10:注册1年以下,20:注册1~5年,30:注册5年以上)
        String bizLicenseYear = ChooseEq.create(apiApplyMessage.getBizLicenseYear())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "30")
                .end("0");
        apiPlatApply.setBizLicenseYear(bizLicenseYear);
        // 经营流水(单位万元)
        String bizBankDetails = ChooseEq.create(apiApplyMessage.getBizBankDetails())
                .when("1", "50")
                .when("2", "100")
                .when("3", "500")
                .end("50");
        apiPlatApply.setBizBankDetails(bizBankDetails);
        // 对公账户收入(单位万元)
        String bizPubAccBankDetails = ChooseEq.create(apiApplyMessage.getBizPubAccBankDetails())
                .when("1", "50")
                .when("2", "100")
                .when("3", "500")
                .end("50");
        apiPlatApply.setBizPubAccBankDetails(bizPubAccBankDetails);
        // 信用卡额度
        String creditLimit = ChooseEq.create()
                .when(apiApplyMessage.getCreditLimit(), "1", "0")
                .when(apiApplyMessage.getCreditLimit(), "2", "10")
                .when(apiApplyMessage.getCreditLimit(), "3", "10")
                .when(apiApplyMessage.getCreditLimit(), "4", "10")
                .when(apiApplyMessage.getCreditLimit(), "5", "10")
                .when(apiApplyMessage.getCreditLimit(), "6", "10")
                .end("0");
        apiPlatApply.setCreditLimit(creditLimit);
        apiPlatApply.setProductId(apiApplyMessage.dataExchangeApplyId());
        // 协议
        apiPlatApply.setAgreementUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyMessage.getProductPlanId(), apiApplyMessage.getPhoneMd5()));
        String aesKey = generateAESKey();
        String encryptedData = encryptData(JsonUtils.toJson(apiPlatApply), aesKey);
        String encryptAesKey = encryptKey(KEY, aesKey);
        JSONObject json = new JSONObject();
        json.put("content", encryptedData);
        json.put("key", encryptAesKey);
        String encryptParam = json.toJSONString();
        String reqParam = Base64.getEncoder().encodeToString(encryptParam.getBytes(StandardCharsets.UTF_8));
        return MapUtils.<String, Object>newHashMap(newMap -> newMap.put("data", reqParam));
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        //  根据文档响应判断
        if (!Eq.object(jsonObject.getInteger("code"), 10000)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }

        //  根据文档响应判断
        Boolean ok = jsonObject.getBoolean("ok");
        if (ok == null || !ok) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        //  根据文档响应判断
        if (!Eq.object(jsonObject.getInteger("code"), 10000)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        //  根据文档响应判断
        Boolean ok = jsonObject.getBoolean("ok");
        if (ok == null || !ok) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(jsonObject.getString("data"));
        JSONArray resProtocolList = resData.getJSONArray("agreementList");
        BigDecimal price = resData.getBigDecimal("settlementPrice");
        String productName = resData.getString("productName");
        String logo = resData.getString("productLogo");
        String orderId = resData.getString("productId");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("name"));
                    protocol.setProtocolUrl(protocolObject.getString("url"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName("优卡数信");
        result.setProductName(productName);
        result.setApplyId(orderId);
        result.setProtocolList(protocolList);
        return result;
    }

    public static String generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        return Base64.getEncoder().encodeToString(keyGenerator.generateKey().getEncoded());
    }

    /**
     * 使用AES密钥加密传输数据
     *
     * @param jsonData json数据
     * @param aesKey   临时密钥
     * @return String
     */
    public static String encryptData(String jsonData, String aesKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(aesKey), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedJson = cipher.doFinal(jsonData.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedJson);
    }

    /**
     * 使用RSA公钥加密随机AES密钥
     *
     * @param publicRSAKey RSA公钥
     * @return String
     */
    public static String encryptKey(String publicRSAKey, String aesKey) throws Exception {
        byte[] publicKeyData = Base64.getDecoder().decode(publicRSAKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyData));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedKey = cipher.doFinal(Base64.getDecoder().decode(aesKey));
        return Base64.getEncoder().encodeToString(encryptedKey);
    }

    /**
     * 解密aesKey原文
     *
     * @param encryptedKey  加密的aesKey
     * @param privateRSAKey rsa私钥
     * @return String
     */
    public static String decryptKey(String encryptedKey, String privateRSAKey) throws Exception {
        byte[] privateKeyData = Base64.getDecoder().decode(privateRSAKey);
        byte[] encryptedAESKey = Base64.getDecoder().decode(encryptedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyData));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedAESKey = cipher.doFinal(encryptedAESKey);
        return Base64.getEncoder().encodeToString(decryptedAESKey);
    }

    /**
     * 解密JSON数据
     *
     * @param encryptedData 加密JSON数据
     * @param encryptedKey  加密key
     * @param privateRSAKey 私钥
     * @return String
     */
    public static String decryptData(String encryptedData, String encryptedKey, String privateRSAKey) throws Exception {
        byte[] encryptJsonData = Base64.getDecoder().decode(encryptedData);
        String aesKey = decryptKey(encryptedKey, privateRSAKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(aesKey), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedJson = cipher.doFinal(encryptJsonData);
        return new String(decryptedJson, StandardCharsets.UTF_8);
    }
}
